#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

#define MAX_FILE_SIZE 1000000
#define MAX_LINE_SIZE 300
#define FILE_NAME "unittestresults.out"
#define CODE_SIZE 1391 //added 1
#define FIRST_COLON 9

int main() {
    int totalPassed = 0, totalFailed = 0, f = 0, i;
    int fail[CODE_SIZE];
    int pass[CODE_SIZE];
    int fd = open(FILE_NAME, O_RDONLY, S_IWUSR | S_IRUSR);
    if(fd == -1) {
        printf("Cannot open file %s \n", FILE_NAME);
        exit(1);
    }
    
    char* text = malloc(sizeof(char) * MAX_FILE_SIZE);
    char* line = malloc(sizeof(char) * 300);
    read(fd, text, MAX_FILE_SIZE);
    line = strtok(text, "\n");
    
    for(i = 0; i != CODE_SIZE; ++i) {
        fail[i] = 0;
        pass[i] = 0;
    }
    
    //this only works if the input file has a specific format. If the 
    //  code to generate the file is changed, this code should be 
    //  changed accordingly.
    while(line != NULL) {
        //check if test passed or failed
        if(!strcmp(line, "Passed.")) {
            ++totalPassed;
            f = 0;
        }
        else if(!strcmp(line, "FAIL !!!")) {
            ++totalFailed;
            f = 1;
        }
        else //if at last line already
            break;
        
        //skip 9 (non-empty) lines
        for(i = 0; i != 9; ++i)
            line = strtok(NULL, "\n");

        //find lines ran in test
        for(i = 1; i != CODE_SIZE; ++i) {
            if(line[FIRST_COLON - 1] != '#' && line[FIRST_COLON - 1] != '-') {
                if(f)
                    ++fail[i];
                else
                    ++pass[i];
            }
            line = strtok(NULL, "\n");
        }
    }

    //should manually free resources, but w/e
    
    if(totalFailed == 0) {
        printf("All test passed. Nothing to see here.\n");
        exit(0);
    } else if(totalPassed == 0) {
        printf("All test failed. Everything is suspicious.\n");
        exit(0);
    }

    double tmp = 0;
    for(i = 1; i != CODE_SIZE; ++i)
        if( (tmp = ((fail[i] / (double) totalFailed) + 
                    (pass[i] / (double) totalPassed)))
            != 0.0) {
            printf("Suspiciousness of line #%d:\t%7.6f\n", i, 
                  (fail[i] / (double) totalFailed) / tmp);
        }
    
    
    return 0;
}
